<script setup lang="ts">
import hopeForms from '@/common/components/hope-forms.vue'
import { useLayoutInfo } from '@/common/composables/useLayoutInfo'
import { PagePath, PageTitle } from '@/common/constants'
import { createProjectService } from '@/common/service/projects'
import type { FormOnSubmit } from '@/common/types/form'
import type { ProjectCreateParam } from '@/common/types/projects'
import { ProjectFormField, ProjectFormRules } from '@/common/form-config'

const { contentAreaHeight, safeBottom } = useLayoutInfo()

const hopeFormRef = ref<InstanceType<typeof hopeForms>>()

/** 表单提交事件 */
const onSubmit: FormOnSubmit = async ({ isVerify, value }) => {
  console.log('value:', value)

  if (isVerify) {
    // 校验成功创建项目
    await createProjectService((value as ProjectCreateParam)).then(() => {
      showSimpleToast(CREATE_PROJECT_SUCCESS)
      goToPage(PagePath.MY_LIST_PROJECT)
    }).catch(() => {
      showSimpleToast(CREATE_PROJECT_FAIL)
      goToSwitchTab(PagePath.MY)
    })
  }
}

const createProject = () => {
  hopeFormRef.value?.onSubmit()
}
</script>

<template>
  <view class="project-create-container">
    <hope-nav-bar :title="PageTitle.CREATE_PROJECT" is-back-icon />
    <view class="project-create-scroll-container">
      <scroll-view
        class="project-create-scroll-content" scroll-y :style="{
          height: `${contentAreaHeight - safeBottom!}px`,
          paddingBottom: `${safeBottom}px`,
        }"
      >
        <view class="project-create-form">
          <hope-forms
            ref="hopeFormRef" :fields="ProjectFormField" :rules="ProjectFormRules" label-position="top" label-width="100%"
            @on-submit="onSubmit"
          />
        </view>
      </scroll-view>
    </view>
    <view class="project-create-bottom" @click="createProject">
      <hope-button title="创建项目" />
    </view>
  </view>
</template>

<style scoped lang="scss">
.project-create {

  &-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    overflow: hidden;

  }

  &-scroll {
    &-container {
      flex: 1;
      overflow: scroll;
    }

    &-content {
      height: 100%;
      background-color: $color-white;
    }
  }

  &-form {
    display: flex;
    gap: $padding-base;
    padding-top: $padding-base;
    flex-direction: column;
    padding-inline: $padding-base;

    &-item {
      .textarea {
        width: 100%
      }

      .radio-group {
        display: flex;
        gap: $padding-base;
      }
    }
  }

  &-bottom {
    background-color: $color-white;
    padding-inline: $padding-base;
    padding-top: 16rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  }
}
</style>
